﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDeviceManager.Models;
using System.Web.Security;
using MvcDeviceManager.ViewModels;
using MvcDeviceManager.Filter;

namespace MvcDeviceManager.Controllers
{
    public class UserController : Controller
    {
        [AuthorizeFilter]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [AuthorizeFilter]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus status;
                Membership.CreateUser(user.UserName, user.Password, "", "question", "answer", true, null, out status);
                if (status == MembershipCreateStatus.Success)
                {
                    //MigrateShoppingCart(model.UserName); 
                    
                    FormsAuthentication.SetAuthCookie(user.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("LogOn", "Login");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(status));
                }
            }
            return View(user);
        }

        public ActionResult ModifyPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ModifyPassword(ModifyPassword modify)
        {
            if (ModelState.IsValid)
            {
                 try
                {
                    if (modify.newpassword.Length < Membership.MinRequiredPasswordLength)
                    {
                        throw new Exception(String.Format("对不起，密码长度不得少于{0}位", Membership.MinRequiredPasswordLength));
                    }
                    MembershipUser user = Membership.GetUser(this.HttpContext.User.Identity.Name);
                   
                    bool flag = user.ChangePassword(modify.oldpassword, modify.newpassword);
                    if (flag)
                    {
                        System.Diagnostics.Trace.WriteLine("admin");
                    }

                    }
                 catch (Exception ex)
                 {
                     ModelState.AddModelError("", ex.Message);
                 }
               
            }
            return View(modify);
        }

        [AuthorizeFilter]
        public ActionResult Role()
        {
            MembershipUserCollection allUsers = Membership.GetAllUsers();
            ViewBag.user= new SelectList(allUsers, "UserName","UserName");
            return View();
        }
        //[AuthorizeFilter]
        public ActionResult UserRoles(string user)
        {
            string[] roles= Roles.GetAllRoles();
            string[] userRoles = Roles.GetRolesForUser(user);
            IList<UserRole> allRoles = new List<UserRole>(roles.Length);
            UserRole ur;
            foreach (string r in roles)
            {
                ur = new UserRole();
                ur.Role = r;
                if (userRoles.Contains(r))
                {
                    ur.HasAuthority = true;
                }
                allRoles.Add(ur);
            }
            return Json(allRoles);
        }
        [AuthorizeFilter]
        public ActionResult SubmitChange(FormCollection form)
        {
            string user = form["user"];
            if (user.Equals("admin"))
            {
                return Json(new {error="对不起，用户admin不能执行此操作！"});
            }
            string[] userRoles = Roles.GetRolesForUser(user);
            if (userRoles.Length > 0)
            {
                Roles.RemoveUserFromRoles(user, userRoles);
            }
            string role = form["role"];
            if (role != null)
            {
                char[] sp = new char[] { ',' };
                string[] roles = role.Split(sp);
                Roles.AddUserToRoles(user, roles);
            }
            return Json("恭喜你修改成功！");
        }
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "请正确输入密码.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }
}
